package br.ufpb.di.knowledgetv.webapp.controllers;

import br.ufpb.di.knowledgetv.sqtv.modules.WorkflowModule;
import br.ufpb.di.knowledgetv.sqtv.utils.Data;
import br.ufpb.di.knowledgetv.sqtv.utils.Result;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * User: manoel
 * Date: 28/06/13
 */

@Controller
@RequestMapping("api/v0")
public class APIV0Controller {

    @Autowired
    private WorkflowModule sqtvModule;

    @RequestMapping("/docs")
    public String docs(Model model){
        model.addAttribute("Teste", "Teste");
        return "docs";
    }

    @RequestMapping(value = "/sqtv/query", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String semanticQuery(@RequestParam(value = "q", required = true, defaultValue = "") String q) {
        JSONArray result = new JSONArray();
        if (q.isEmpty()) {
            JSONObject object = new JSONObject();
            this.addValueToJson(object, "empty", true);
            result.put(object);
        }

        Data resultData = sqtvModule.start(q);
        List<Result> resourceList = (List<Result>) resultData.getData("final_result");

        for (Result r : resourceList) {
            JSONObject object = new JSONObject();

            for(Object fieldName : r.getFieldNames()) {
                this.addValueToJson(object, (String) fieldName, r.get((String) fieldName));
            }

            result.put(object);
        }

        return result.toString();
    }


    private void addValueToJson(JSONObject object, String key, Object value) {
        try {
            object.put(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}